package st.learnopengl.apps.assets

import gln.identifiers.GlProgram
import gln.vertexArray.GlVertexArray
import org.lwjgl.assimp.AIMaterial
import org.lwjgl.assimp.AIMesh
import org.lwjgl.assimp.AIScene
import org.lwjgl.assimp.Assimp

class Model(var scene: AIScene) {

    val meshes: ArrayList<Mesh> = ArrayList()
    val materials: ArrayList<Material> = ArrayList()

    var vao: GlVertexArray? = null

    init {
        val meshesBuffer = scene.mMeshes()

        for (i in 0 until scene.mNumMeshes()) {
            meshes.add(Mesh(AIMesh.create(meshesBuffer!!.get(i)), this))
        }

        val materialsBuffer = scene.mMaterials()

        for (i in 0 until scene.mNumMaterials()) {
            materials.add(Material(AIMaterial.create(materialsBuffer!!.get(i))))
        }
    }

    fun build() {

        vao = GlVertexArray.gen()
        vao!!.bound {

            meshes.forEach {
                it.build()
            }

            materials.forEach {
                it.build()
            }
        }
    }

    fun free() {
        Assimp.aiReleaseImport(scene)

    }


    fun render(program: GlProgram, runningTime: Float) {

        vao!!.bound {

            meshes.forEach {
                it.render(program, runningTime)
            }

            materials.forEach {
                it.unbind()
            }
        }
    }
}